package com.heima.datasync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.search.SearchConstants;
import com.heima.common.exception.CustException;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public ResponseResult dataInit() {


        try {
            // 分页查询第一页文章数据
            List<ApArticle> articleList = apArticleMapper.findAllArticles();
            if (articleList==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有满足条件的数据");
            }
            BulkRequest bulkRequest = new BulkRequest(SearchConstants.ARTICLE_INDEX_NAME);
            // 遍历页码批量插入到索引库
            for (ApArticle apArticle : articleList) {
                // 封装数据
                SearchArticleVo searchArticleVo = new SearchArticleVo();
                BeanUtils.copyProperties(apArticle,searchArticleVo);
                IndexRequest indexRequest = new IndexRequest();
                // 设置文档ID
                indexRequest.id(String.valueOf(apArticle.getId()));
                // 转json
                indexRequest.source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
                // 添加到批量插入对象
                bulkRequest.add(indexRequest);
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return ResponseResult.okResult(bulk.status());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }
}
